import types from './types'
import * as server from '@/service/api'
import io from 'socket.io-client'
import {
  ElMessage,
  ElNotification as Notify
} from 'element-plus'
import config from '@/service/config'
let socket = null

export default {
  async _postDelOrderHistory({
    dispatch,
    commit,
    state
  }, params = {}) {
    let res = await server._postDelOrderHistory(params)

    return res && res.status === 200 ? res : null
  },
  async _postOrderHistoryList({
    dispatch,
    commit,
    state
  }, params = {}) {
    let res = await server._postOrderHistoryList(params)

    return res && res.status === 200 ? res : null
  },
  async _postAddOrderHistory({
    dispatch,
    commit,
    state
  }, params = {}) {
    let res = await server._postAddOrderHistory(params)

    return res && res.status === 200 ? res : null
  },
  async _getSearchSuggest({
    dispatch,
    state
  }, params = {}) {
    let res = await server._getSearchSuggest(params)
    if (res && res.code === 200) {

      let data = []
      let result = res.result
      let songs = result.songs ? result.songs.map(v => {
        return {
          value: v.name
        }
      }) : []
      let playlists = result.playlists ? result.playlists.map(v => {
        return {
          value: v.name
        }
      }) : []
      let artists = result.artists ? result.artists.map(v => {
        return {
          value: v.name
        }
      }) : []
      let albums = result.albums ? result.albums.map(v => {
        return {
          value: v.name
        }
      }) : []
      data = [...songs, ...playlists, ...artists, ...albums]
      return data

    }
    return res && res.code === 200 ? res : null
  },
  async _getSearchHot({
    dispatch,
    state
  }, params = {}) {
    let res = await server._getSearchHot(params)
    return res && res.code === 200 ? res : null
  },
  async _getSongLyric({
    dispatch,
    state,
    commit
  }, params = {}) {
    if (state.songInfo.id) {

      let res = await server._getSongLyric({
        id: state.songInfo.id
      })
      await commit('SET_STATE', {
        key: 'lyric',
        value: res.nolyric ? '' : res.lrc.lyric
      })
      if (res.nolyric) {
        await commit('SET_STATE', {
          key: 'currentLyric',
          value: null
        })
      }
      return res && res.code === 200 ? res : null
    } else {
      return null
    }
  },
  async fetchNewSong({
    dispatch,
    state
  }, params = {}) {
    let res = await server._getNewsong(params)
    return res && res.code === 200 ? res : null
  },
  async _postChatList({
    dispatch,
    commit,
    state
  }, params = {}) {
    let res = await server._postChatList()
    if (res && res.status === 200) {
      commit('SET_STATE', {
        key: 'chatList',
        value: res.data
      })
    }
    return res && res.status === 200 ? res : null
  },
  async _postEditUser({
    dispatch,
    state,
    commit
  }, params = {}) {
    let res = await server._postEditUser({
      ...params
    })
    if (res && res.status === 200) {
      commit('SET_STATE', {
        key: 'cardShow',
        value: false
      })
    }
    return res && res.status === 200 ? res : null
  },
  async _postTopSong({
    dispatch
  }, params = {}) {
    let res = await server._postTopSong(params)
    if (res && res.status == 200) {
      dispatch('updateOrderList')
    }
    return res && res.status === 200 ? res : null
  },
  async _getNowSong({
    dispatch
  }, params = {}) {
    let res = await server._getNowSong(params)
    return res && res.status === 200 ? res : null
  },
  async fetchSearchSong({
    dispatch
  }, params = {}) {
    let res = await server._getSongSearch(params)
    return res && res.code === 200 ? res : null
  },
  async _getSongCanUse({
    dispatch
  }, params = {}) {
    let res = await server._getSongCanUse(params)
    if (!res) {
      ElMessage.warning({
        showClose: true,
        message: '亲爱的,暂无版权',
        type: 'warning'
      })
    }
    return res
  },
  async _postLogin({
    dispatch,
    state,
    commit
  }, params = {}) {
    let res = await server._postLogin(params)

    commit('SET_STATE', {
      key: 'userInfo',
      value: res.data || {}
    })
    if (res && res.status == 200) {
      commit('SET_STATE', {
        key: 'cardShow',
        value: false
      })
      socket.emit('online', {
        ...state.userInfo
      })
    }
    return res
  },
  async _postRegister({
    dispatch,
    commit
  }, params = {}) {
    let res = await server._postRegister(params)
    commit('SET_STATE', {
      key: 'userInfo',
      value: res.data || {}
    })
    if (res && res.status == 200) {
      commit('SET_STATE', {
        key: 'cardShow',
        value: false
      })
    }
    return res
  },
  async _postUserDetail({
    dispatch,
    state,
    commit
  }, params = {}) {
    let res = await server._postUserDetail()
    await commit('SET_STATE', {
      key: 'userInfo',
      value: res.data || {}
    })
    if (params.type == 'edit') {
      socket.emit('online', {
        ...state.userInfo
      })
      socket.emit('sendMsg')
    }
    return res
  },
  async _postLogout({
    dispatch,
    commit,
    state
  }, params = {}) {
    let res = await server._postLogout(params)
    if (res && res.status == 200) {
      commit('SET_STATE', {
        key: 'cardShow',
        value: false
      })
      socket.emit('offline', {
        ...state.userInfo
      })
    }
    commit('SET_STATE', {
      key: 'userInfo',
      value: {}
    })
    return res
  },
  async _postAddSongOrder({
    dispatch,
    state
  }, params = {}) {
    // if (state.songOrderList.length == 0) {
    //   await dispatch('_postSongOrdeList')
    //   if (state.songOrderList.length == 0) {

    //     state.songInfo = {
    //       artist: params.artist,
    //       name: params.name,
    //       picUrl: params.picUrl,
    //       id: params.songId
    //     }
    //   }
    // }
    let res = await server._postAddSongOrder(params)
    if (res && res.status == 200) {

    }
    return res && res.status == 200 ? res : null
  },
  async _postSongOrdeList({
    commit
  }, params = {}) {
    let res = await server._postSongOrdeList(params)
    commit('SET_ORDER_LIST', res.data || [])
    return res && res.status == 200 ? res : null
  },
  async _postDelSongOrder({
    commit,
    state,
    dispatch
  }, params = {}) {

    let res = await server._postDelSongOrder({
      id: state.songInfo.id
    })
    if (res && res.status == 200) {
      if (res.data == 0) {
        ElMessage.warning({
          showClose: true,
          message: '没有歌曲可以切了,快去点歌吧',
          type: 'warning'
        })
        return
      }
      await dispatch('_postSongOrdeList')
      if (state.songOrderList.length) {

        state.songInfo = {
          artist: state.songOrderList[0].artist,
          name: state.songOrderList[0].name,
          picUrl: state.songOrderList[0].picUrl,
          id: state.songOrderList[0].songId
        }
      }
    }
    return res && res.status == 200 ? res : null
  },
  notifyTitle({ }, params = {}) {
    //标题栏闪动
    let timer = null
    var defaultTitle = document.title;
    timer = setInterval(function () {
      var title = document.title;
      if (document.hidden) {
        if (/来消息啦/.test(title) == false) {
          document.title = '来消息啦';
        } else {
          document.title = defaultTitle;
        }
      } else {
        clearInterval(timer)
        document.title = defaultTitle;
      }
    }, 500);

  },
  notifyMe({
    commit,
    state,
    dispatch
  }, params = { username: '', msg: '' }) {
    // 先检查浏览器是否支持
    if (!("Notification" in window)) {
      console.log("This browser does not support desktop notification");
    }

    // 检查用户是否同意接受通知
    else if (Notification.permission === "granted") {
      var notification = new Notification(params.username, {
        body: params.msg,
        // icon: 'http://image.zhangxinxu.com/image/study/s/s128/mm1.jpg',

      });
      notification.onclick = function () {
        window.focus();//打开对应的页面
        notification.close();//关闭提示信息
      };
      //定时关闭
      notification.onshow = function () {//定时关闭
        setTimeout(notification.close.bind(notification), 3000);
      }
    }

    // 否则我们需要向用户获取权限
    else if (Notification.permission !== 'denied') {
      Notification.requestPermission(function (permission) {
        // 如果用户同意，就可以向他们发送通知
        if (permission === "granted") {
          var notification = new Notification('系统消息', {
            body: '已经允许通知。'
          });
        }
      });
    }

  },
  initSocket({
    commit,
    state,
    dispatch
  }) {
    socket = io(config.websocket)
    socket.on('connect', () => {
      const id = socket.id
      let flag = true
      let item = {}
      console.log('socket id:', id)
      // if (state.userInfo.id) {

      socket.emit('online', {
        ...state.userInfo
      })
      // }

      socket.on('playSong', async data => {
        // console.log('res:', data)
        if (data) {
          let {
            artist,
            name,
            picUrl,
            songId,
            since,
            duration,
            nowDuration
          } = data
          item = {
            artist: artist,
            name: name,
            picUrl: picUrl,
            id: songId,
            since: since,
            duration: duration,
            nowDuration: nowDuration,
            username: data.user.username
          }
          commit('SET_STATE', {
            key: 'songInfo',
            value: item
          })
          flag = true
        } else {
          if (flag) {

            await dispatch('_postSongOrdeList')
            if (!state.songOrderList.length) {
              commit('SET_STATE', {
                key: 'songInfo',
                value: {}
              })
              flag = false
            } else {
              flag = true
            }
          }
        }
      })
      socket.on('updateOrderList', () => {
        console.log('updateOrderList')
        dispatch('_postSongOrdeList')
      })
      socket.on('recMsg', (msg) => {
        // console.log(msg)
        if (msg.length > state.chatList.length) {
          let lastMsg = msg[msg.length - 1]
          let dingdong = document.getElementById('noticePlayer')
          if (lastMsg.userId != state.userInfo.id) {
            dingdong && dingdong.play()
            if (document.hidden) {

              dispatch('notifyMe', { username: state.userInfo.username, msg: lastMsg.msg })
              dispatch('notifyTitle')
            }
          }
        }
        commit('SET_STATE', {
          key: 'chatList',
          value: msg
        })
      })
      socket.on('online', msg => {
        // console.log('online from server: %s!', JSON.stringify(msg));
        let arr = []
        if (msg && msg[0] != null) {
          let data = msg.filter((v) => {
            return v.username != null
          })
          let obj = {}
          arr = data.reduce(function (item, next) {
            obj[next.id] ? '' : obj[next.id] = true && item.push(next);
            return item;
          }, [])
          commit('SET_STATE', {
            key: 'online',
            value: arr || []
          })
        } else {
          commit('SET_STATE', {
            key: 'online',
            value: []
          })
        }

      });

    })

    socket.on('disconnect', data => {
      console.log('disconnect:', data)
    })
  },
  updateOrderList() {
    socket.emit('updateOrderList')
  },
  sendMsg({
    state
  }, params = {}) {
    console.log(state.userInfo.id)
    if (!state.userInfo.id) {
      return false
    }
    socket.emit('sendMsg', {
      ...params,
      userId: state.userInfo.id
    })
    return true
  },
  disconnect() {
    socket.disconnect()
  }





}